/**
* <p>Title: ReadLog.java</p>
* <p>Description: </p>
* <p>Company: www.huoyunren.com</p>
* @author duanxiangyun
* @date 2016年8月25日
* @version 1.0
*/
package com.hxbd.test.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Vector;

import com.duan.test.utils.common.CommonUtils;
import com.duan.test.utils.common.JschUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class JschHandler {
	
	private static Session session;
	
	/**
	 * 无key验证
	 * @param ip
	 * @param user
	 * @param psw
	 * @param port
	 */
	public JschHandler (String ip, String user, String psw, String port) {
		try {
			session = JschUtils.sshShell(ip, user, psw, port, "", "");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 需要key 验证
	 * @param ip ip
	 * @param user 服务器用户
	 * @param psw 密码
	 * @param port 端口
	 * @param privateKey 私钥（绝对路径）
	 * @param passphrase 私钥对应密码
	 */
	public JschHandler (String ip, String user, String psw, String port, String privateKey, String passphrase) {
		try {
			session = JschUtils.sshShell(ip, user, psw, port, privateKey, passphrase);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 执行一个或多个cmd命令(以;分隔)，返回最后一个comand的结果
	 * @param cmd 一个或多个cmd命令(以;分隔)
	 * @param charset 返回结果的编码格式
	 * @return String
	 */
	public String exccmd (String cmd,String charset) {
    	Channel channel = null; 
    	String tmp="";
		try {		
			//创建sftp通信通道
	        channel = (Channel) session.openChannel("shell");
	        channel.connect(1000);
	        //获取输入流和输出流
	        OutputStream outstream = channel.getOutputStream();         
	        //发送需要执行的SHELL命令，需要用\n结尾，表示回车

	        String []cmds = cmd.split(";");
	        for (int i = 0; i < cmds.length; i++) {
	        	outstream.write((cmds[i]+"\n").getBytes());
		        outstream.flush();
	        } 
	        while (channel.isEOF()) {
	        	break;
	        }
	        InputStream instream = channel.getInputStream();	        
	        //获取命令执行的结果
	        for (int i = 0; i <= 10; i++) {
	        	if (instream.available() <= 0) {
	        		Thread.sleep(1000);
	        	}
	        	else {
	        		break;
	        	}
	        }
            byte[] data = new byte[instream.available()];
            int nLen = instream.read(data);         
            if (nLen < 0) {
                throw new Exception("network error.");
            }            
            //转换输出结果并打印出来
            String temp = new String(data, 0, nLen,"UTF-8");
            String[] s = temp.split("\r\n");
            int count = 0;
           
            for (int i = s.length-1; i >= 0; i--) {
            	if (s[i].startsWith("[") && s[i].contains("@") && s[i].contains("]")) {
            		count++;
            	}
            	else {
            		tmp += s[i]+"\r\n";
            	}
            	if (count == 2) {
            		break;
            	}
            }
            System.out.println(tmp);
	        outstream.close();
	        instream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			channel.disconnect();
			session.disconnect();
		}
		return tmp;
	}
	
	 /**
     * 在远程服务器上执行命令
     * 已过时：请用exccmd替代
     * @param cmd 要执行的命令字符串
     * @param charset 编码
     * @throws Exception
     */
	@Deprecated
    public void runCmd(String cmd,String charset) throws Exception{ 
    	Channel c = session.openChannel("exec");
    	ChannelExec channelExec = (ChannelExec)c ;
        channelExec.setCommand(cmd);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        InputStream in = channelExec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
        String buf = null;
        while ((buf = reader.readLine()) != null){
            System.out.println(buf);
        }
        System.out.println(11);
        reader.close();
        c.disconnect();
    }
    
    /**
     * 上传文件
     *
     * @param directory
     *            上传的目录
     * @param uploadFile
     *            要上传的文件
     * @param sftp
     * @throws JSchException
     * @throws SftpException
     * @throws FileNotFoundException
     */
    public void upload(String directory, String uploadFile) throws JSchException, FileNotFoundException, SftpException {
    	
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.cd(directory);
        File file = new File(uploadFile);
        channelSftp.put(new FileInputStream(file), file.getName());
        System.out.println("Upload Success!");
    }

    /**
     * 下载文件
     * 
     * @param src
     * @param dst
     * @throws JSchException
     * @throws SftpException
     */
    public void download(String src, String dst) throws JSchException, SftpException {
        // src linux服务器文件地址，dst 本地存放地址
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.get(src, dst);
        channelSftp.quit();
    }

    /**
     * 删除文件
     *
     * @param directory
     *            要删除文件所在目录
     * @param deleteFile
     *            要删除的文件
     * @param sftp
     * @throws SftpException
     * @throws JSchException
     */
    public void delete(String directory, String deleteFile) throws SftpException, JSchException {
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.cd(directory);
        channelSftp.rm(deleteFile);
    }

    /**
     * 列出目录下的文件
     *
     * @param directory
     *            要列出的目录
     * @param sftp
     * @return
     * @throws SftpException
     * @throws JSchException
     */
    @SuppressWarnings("rawtypes")
    public static Vector listFiles(String directory) throws JSchException, SftpException {
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        return channelSftp.ls(directory);
    }

	public static void main(String[] args) {
        String shellCommand = "ls;sudo su -;find / -type f -name \"rmq_bk_gc.log\" | xargs grep \"GC2016-07-19T04:42:04.201+0800\"";
        JschHandler js = new JschHandler("172.16.1.54", "liulin", "123456", "22", CommonUtils.getFilePath("/Config/id_rsa_2048.2048"), "123456");
        js.exccmd(shellCommand, "utf-8");		
	}
}
